<?php
/*
 * 进云智能生成平台
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
 * 小程序端，小程序端不会自动发送cookie，需要手动发送sessionID，此处访问首页，成功则返回sessionID，失败则返回0
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'login';
if(!$_SESSION['token']){
	$_SESSION['token']=random(30);
}
$_SESSION['wxapp_id']=$_SESSION['appgid']=intval($_RQ['wxgid']);
if(!$_SESSION['wxapp_id']){
	exit('没有传小程序ID！');
}
if($_SESSION['wxappopenid'] && !$_RQ['wxgid']){
	return false;
}
$wxapp=pdo_get('core_account_wxapp',array('id'=>$_SESSION['wxapp_id'],'uniacid'=>1));
if(!$wxapp['id']){
	exit('系统平台，没有找到该小程序！');
}
if($_RQ['op']=='login'){
	if($_RQ['code']){
		//如果有code，根据code获取粉丝openid
		$url='https://api.weixin.qq.com/sns/jscode2session?appid='.$wxapp['appid'].'&secret='.$wxapp['appsecret'].'&js_code='.$_RQ['code'].'&grant_type=authorization_code';
		$result=cfc('http')->ihttp_get($url);
		if(is_error($result)){
			exit('获取粉丝信息失败：'.$result['message']);
		}
		$result=json_decode($result['content'],true);
		if($result['openid']){
			if($_SESSION['openid'] && $_SESSION['fromh5wxapp']==1 && $_SESSION['openid']!=$result['openid']){
				//保留公众号openid
				$_SESSION['wechatopenid']=$_SESSION['openid'];
			}
			$_SESSION['openid']=$result['openid'];
			$_SESSION['wxappopenid']=$result['openid'];
			$_SESSION['session_key']=$result['session_key'];
			$mid=false;
			if($result['unionid']){
				$_SESSION['unionid']=$result['unionid'];
				$mid=pdo_getcolumn('core_members',array('unionid'=>$result['unionid'],'uniacid'=>1),'id');
			}
			$fans=pdo_get('core_fans',array('openid'=>$_SESSION['openid'],'uniacid'=>1,'wxgid'=>$_SESSION['wxapp_id']),array('id','mid'));
			if($fans){
				if(!$mid && $fans['mid']){
					$mid= $fans['mid'];
				}
			}else{
				$fansdata=array(
					'uniacid'=>1,
					'wxgid'=>$_SESSION['wxapp_id'],
					'openid'=>$_SESSION['openid'],
					'type'=>1,
					'createtime' => TIMESTAMP,
				);
				if($mid){
					$fansdata['mid']=$mid;
				}
				if($result['unionid']){
					$fansdata['unionid']=$result['unionid'];
				}
				pdo_insert('core_fans',$fansdata);
			}
			if($mid){
				model('core/member')->login($mid);
			}
		}
		$sid=session_id();
		if(!$_SESSION['base_key_str']){
			$_SESSION['base_key_str']=str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_');
		}
		$return=array('ssid'=>$sid,'session_key'=>$_SESSION['session_key'],'openid'=>$_SESSION['openid'],'uid'=>$_SESSION['uid'],'token'=>$_SESSION['token'],'base_key_str'=>$_SESSION['base_key_str']);
		exi($return);
	}
}